package com.baidu.controller.servlet;
import com.baidu.Service.StudentService;
import com.baidu.Service.impl.StudentServiceImpl;
import com.baidu.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AddServlet extends HttpServlet {
    //创建service对象
    StudentService as =  new StudentServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加学生的姓名
        String username = req.getParameter("username");
        //获取添加学生的年龄
        String age = req.getParameter("age");
        //获取添加学生的成绩
        String score = req.getParameter("score");
        //创建学生类对象，封装数据
        Student stu = new Student(username,Integer.parseInt(age),Integer.parseInt(score));
        //调用service层添加学生的方法添加数据，并且返回学生是否添加成功
        boolean result = as.addStudent(stu);
        if (result)
        {
            req.setAttribute("add",req.getSession().getAttribute("username"));
            resp.getWriter().write("添加学生信息成功，2秒后将跳转首页");
            String path = req.getContextPath();
            resp.setHeader("Refresh","2;"+path+"/index.jsp");
        }else {
            resp.getWriter().write("添加学生信息失败");
        }
        //获取虚拟目录的名称

        //重定向首页


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
